package com.yxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.context.BaseContext;
import com.yxy.exception.AddInfoException;
import com.yxy.mapper.BookMapper;
import com.yxy.mapper.RateMapper;
import com.yxy.pojo.dto.BookDTO;
import com.yxy.pojo.dto.PageQueryDTO;
import com.yxy.pojo.dto.TypeDTO;
import com.yxy.pojo.entity.Book;
import com.yxy.pojo.vo.BookDetailVO;
import com.yxy.pojo.vo.BookPageQueryVO;
import com.yxy.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private RateMapper rateMapper;

    /**
     * 分页查询图书
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(PageQueryDTO pageQueryDTO) {
        // 该行代码使用了MyBatis分页插件PageHelper来设置分页参数。
        // 功能是启动一个分页查询，设置当前页为pageQueryDTO.getPage()，每页显示条数为pageQueryDTO.getPageSize()。
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<BookPageQueryVO> page = bookMapper.queryByPage(pageQueryDTO);
        page.getResult().forEach(item -> {
            List<Integer> bookRateList = rateMapper.getRateAll("book", item.getId());
            double rateSum = bookRateList.stream().mapToDouble(rate -> rate).sum();
            if(rateSum != 0){
                item.setRate(rateSum / bookRateList.size() / 2);
            }
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增图书
     */
    @Override
    public void add(BookDTO bookDTO) {
        // 判断是否已存在
        Book b = bookMapper.selectByTitle(bookDTO.getTitle());
        if(b != null){
            throw new AddInfoException("图书已存在！");
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        book.setCreateTime(LocalDate.now());
        book.setCreateUser(BaseContext.getCurrentId());
        bookMapper.addBook(book);
    }

    /**
     * 根据id查询书籍信息
     * @param id
     */
    @Override
    public BookDetailVO getById(int id) {
        return bookMapper.selectById(id);
    }

    /**
     * 修改图书
     * @param bookDTO
     */
    @Override
    public void update(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        book.setUpdateUser(BaseContext.getCurrentId());
        book.setUpdateTime(LocalDate.now());
        bookMapper.updateBook(book);
    }
}
